<?php
ini_set("soap.wsdl_cache_enabled", "0");
header('Content-Type: text/xml; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load_old("nn_logic/nl_common.func.php");
\ns_core\m_load::load_old("nn_logic/nl_log_v2.func.php");
\ns_core\m_load::load_old("nn_logic/cp/cp.class.php");
\ns_core\m_load::load_old("nn_logic/message/nl_message.class.php");
\ns_core\m_load::load_old("mgtv_v2/models/import_model.php");
\ns_core\m_load::load_old("nn_class/encrypt/encrypt_aes.class.php");
$arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
$str_dir = array_pop($arr_dir);
define('ORG_ID', $str_dir);
define('DEFAULT_SOURCE_ID', $str_dir);
\m_config::write_message_receive_log("-----------Start索贝注入的消息接收开始-----------", DEFAULT_SOURCE_ID);
/**
 * 索贝媒资注入SOAP接口处理类
 * @author chunyang.shu
 * @date 2017-09-19
 */
class soap_import
{
    /**
     * 消息返回状态码：成功
     */
    const STATE_OK = 0;
    /**
     * 消息返回状态码：包数据格式不正确
     */
    const STATE_DATA_FORMAT_ERROR = -10001;
    /**
     * 消息返回状态码：数据校验不正确
     */
    const STATE_DATA_CHECK_ERROR = -10002;
    /**
     * 消息返回状态码：系统内部错误
     */
    const STATE_DATA_SYSTEM_ERROR = 2;
    /**
     * 消息ID
     */
    protected $str_message_id;
    /**
     * 节目入库服务
     * @param string $program_info 节目内容xml
     * @return string 返回结果xml
     * @author chunyang.shu
     * @date 2017-09-19
     */
    public function ProgramImport($program_info)
    {
        // 记录接口请求日志
        \m_config::write_message_receive_log("索贝媒资注入，节目入库服务接口，节目数据为：" . var_export($program_info, 1), DEFAULT_SOURCE_ID);
        $re = $this->add_message(ORG_ID, $program_info);
        return $re;
    }
    /**
     * @param $cp_id
     * @param $program_info     接收到最原始的SOAP数据
     */
    public function add_message($cp_id,$program_info)
    {
        //加载 xml转为数组的np库
        \ns_core\m_load::load_np("np_xml2array.class.php");
        //1、将xml数据转换为数组
        $obj_dom = new DOMDocument('1.0', 'utf-8');
        $obj_dom->loadXML($program_info);
        $arr_data = np_xml2array::getArrayData($obj_dom->saveXML());
        if ($arr_data['ret'] == 0)
        {
            \m_config::write_message_receive_log("xml数据转换为数组失败，最原始xml数据为：{$program_info}", DEFAULT_SOURCE_ID);
            return $this->_create_message_response(self::STATE_DATA_FORMAT_ERROR);
        }
        //2、获取消息ID
        if (is_array($arr_data['data']['children']) && !empty($arr_data['data']['children']))
        {
            $arr_request_list = np_array_rekey($arr_data['data']['children'], 'name');
            if (is_array($arr_request_list['Head']['children']) && !empty($arr_request_list['Head']['children']))
            {
                $arr_head_list = np_array_rekey($arr_request_list['Head']['children'], 'name');
                if (isset($arr_head_list['TaskGUID']['content']) && strlen($arr_head_list['TaskGUID']['content']))
                {
                    $arr_task_guid_info = explode('-', $arr_head_list['TaskGUID']['content']);
                    $this->str_message_id = isset($arr_task_guid_info[1]) ? $arr_task_guid_info[1] : '';
                }
            }
        }
        if (strlen($this->str_message_id) == 0)
        {
            \m_config::write_message_receive_log("Head中的TaskGUID格式错误，不能得到消息ID", DEFAULT_SOURCE_ID);
            return $this->_create_message_response(self::STATE_DATA_CHECK_ERROR);
        }
        //3、获取CP消息
        $arr_cp_info = nl_cp::query_by_id(m_config::get_dc(), $cp_id);
        if ($arr_cp_info['ret'] != 0)
        {
            \m_config::write_message_receive_log("根据CPID获取CP消息，数据库执行失败，CP ID为：{$cp_id}", DEFAULT_SOURCE_ID);
            return $this->_create_message_response(self::STATE_DATA_SYSTEM_ERROR);
        }
        if (!is_array($arr_cp_info['data_info']) || empty($arr_cp_info['data_info']))
        {
            \m_config::write_message_receive_log("根据CPID获取CP消息，CP不存在，CPID为：{$cp_id}", DEFAULT_SOURCE_ID);
            return $this->_create_message_response(self::STATE_DATA_SYSTEM_ERROR);
        }
        list($str_usec, $str_sec) = explode(' ', microtime());
        $str_microtime = date('YmdHis') . str_pad(intval(substr($str_usec, 2, 4)), 4, '0', STR_PAD_LEFT);//获取毫秒级时间
        //4、组装消息数据
        $arr_message_data = array(
            'nns_id'                => np_guid_rand(),
            'nns_message_time'      => $str_microtime,
            'nns_message_id'        => $this->str_message_id,
            'nns_message_xml'       => '',
            'nns_message_content'   => addslashes($obj_dom->saveXML()),
            'nns_message_state'     => '0',
            'nns_create_time'       => date('Y-m-d H:i:s'),
            'nns_again'             => 0,
            'nns_delete'            => 0,
            'nns_cp_id'             => $cp_id
        );
        //5、添加消息
        \m_config::write_message_receive_log("添加消息，添加数据：" . var_export($arr_message_data, true), DEFAULT_SOURCE_ID);
        $arr_add_result = nl_message::add(m_config::get_dc(), $arr_message_data);
        file_put_contents('a.txt',var_export($arr_add_result,1));
        if ($arr_add_result['ret'] != 0)
        {
            \m_config::write_message_receive_log("消息添加失败，原因：" . $arr_add_result['reason'], DEFAULT_SOURCE_ID);
            return $this->_create_message_response(self::STATE_DATA_SYSTEM_ERROR);
        }
        // 返回结果
        return $this->_create_message_response(self::STATE_OK);
    }
    /**
     * 组装消息处理返回结果
     * @param string $ret 状态码，0表示成功，-10001表示包数据格式不正确，-10002表示数据校验不正确
     * @return string xml结果
     * @author chunyang.shu
     * @date 2017-09-19
     */
    protected function _create_message_response($ret)
    {
        // dom
        $obj_dom = new DOMDocument('1.0', 'utf-8');
        // ProgramImportResponse
        $obj_response = $obj_dom->createElement('ProgramImportResponse');
        // Head
        $obj_head = $obj_dom->createElement('Head');
        // TaskGUID
        $obj_item = $obj_dom->createElement('TaskGUID');
        $obj_text = $obj_dom->createTextNode($this->str_system_code . '-' . $this->str_message_id);
        $obj_item->appendChild($obj_text);
        $obj_head->appendChild($obj_item);
        // TaskFlowType
        $obj_item = $obj_dom->createElement('TaskFlowType');
        $obj_text = $obj_dom->createTextNode('');
        $obj_item->appendChild($obj_text);
        $obj_head->appendChild($obj_item);
        // TaskCurrentGUID
        $obj_item = $obj_dom->createElement('TaskCurrentGUID');
        $obj_text = $obj_dom->createTextNode('');
        $obj_item->appendChild($obj_text);
        $obj_head->appendChild($obj_item);
        // TaskPreStepGUID
        $obj_item = $obj_dom->createElement('TaskPreStepGUID');
        $obj_text = $obj_dom->createTextNode('');
        $obj_item->appendChild($obj_text);
        $obj_head->appendChild($obj_item);
        // UserToken
        $obj_item = $obj_dom->createElement('UserToken');
        $obj_text = $obj_dom->createTextNode('');
        $obj_item->appendChild($obj_text);
        $obj_head->appendChild($obj_item);
        // SourceSystemID
        $obj_item = $obj_dom->createElement('SourceSystemID');
        $obj_text = $obj_dom->createTextNode('');
        $obj_item->appendChild($obj_text);
        $obj_head->appendChild($obj_item);
        // ProgramImportResponse填充Head
        $obj_response->appendChild($obj_head);
        // Result
        $obj_item = $obj_dom->createElement('Result');
        $obj_text = $obj_dom->createTextNode($ret);
        $obj_item->appendChild($obj_text);
        // ProgramImportResponse填充Result
        $obj_response->appendChild($obj_item);
        // dom填充ProgramImportResponse
        $obj_dom->appendChild($obj_response);
        // 返回结果
        return $obj_dom->saveXML();
    }
}
// 创建SOAP服务
$obj_server = new SoapServer("ProgramService.wsdl");
$obj_server->setClass('soap_import');
$obj_server->handle();
\m_config::write_message_receive_log("-----------End接收索贝注入消息结束-----------", DEFAULT_SOURCE_ID);